import type { TabsPaneContext } from 'element-plus-cisdi';
import type { AppIdsMap, ChildComponentMethods, MiTreeSelectorInstance, PermissionItem, RoleData, RoleSaveRequest, SelectedPermissions, TransferParams, TransformedPermissionItem, TreeNodeCharacter } from '@/types/RoleAuthorization';
import { ElMessage } from 'element-plus-cisdi';
import { nextTick, reactive, ref } from 'vue';
import { getRoleAuthorizationAllList, getRoleAuthorizationInheritanceList, getRoleAuthorizationList, getRoleAuthorizationSave } from '@/api/RoleAuthorizationDialog';
import { useTreeData } from './UseTreeData';

// 角色授权主逻辑 Hook
export function useRoleAuthorization() {
  const treeInheritanceData = ref();
  const treeAllData = ref();
  const paramsTree = ref();
  const loading = ref(false);
  const inheritanceRef = ref<ChildComponentMethods | null>(null);
  const allRef = ref<ChildComponentMethods | null>(null);
  const { treeData, appCodeArray, functionalResult, treeAddSelect, treeSelectorRefs, activePermissionTab, setTreeData } = useTreeData();

  // 响应式数据
  const activePermissionType = ref('all');
  const roleId = ref('');
  const orgCode = ref('');

  const formData = reactive<RoleData>({
    roleCode: '',
    roleName: '',
    responsibilityScope: '',
    description: '',
    orgLevel: '',
    inheritedOrgName: '',
    inheritedRoleName: '',
  });

  const selectedPermissions = reactive<SelectedPermissions>({
    function: [],
    data: [],
    admin: [],
    column: [],
  });

  const propsConfig = {
    key: 'id',
    label: 'name',
    children: 'children',
  };

  // 获取分配权限数据
  const requestTreeData = async (params: TransferParams) => {
    loading.value = true;
    try {
      const res = await getRoleAuthorizationList(params);
      setTreeData(res.data);
      return res.data;
    } catch (error) {
      console.error(error);
      throw error;
    } finally {
      loading.value = false;
    }
  };
  // 处理继承的数据，转换label成name
  function replaceNameWithLabel(items: PermissionItem[]): TransformedPermissionItem[] {
    return items.map((item) => {
      const { name, children, ...rest } = item;
      const newItem: TransformedPermissionItem = {
        ...rest,
        label: name,
      };
      if (children && Array.isArray(children)) {
        newItem.children = replaceNameWithLabel(children);
      }
      return newItem;
    });
  }
  // 获取全部权限的数据
  const requesAllTreeData = async (params: TransferParams) => {
    loading.value = true;
    try {
      const res = await getRoleAuthorizationAllList(params);
      treeAllData.value = replaceNameWithLabel(res.data);
      loading.value = false;
      return res.data;
    } catch (err) {
      console.error(err);
      throw err; // 仍然抛出错误，但先进行了处理
    } finally {
      loading.value = false; // 结束加载
    }
  };

  // 获取继承的权限的数据
  const requestInheritanceTreeData = async (params: TransferParams) => {
    loading.value = true;
    try {
      const res = await getRoleAuthorizationInheritanceList(params);
      treeInheritanceData.value = replaceNameWithLabel(res.data);
      return res.data;
    } catch (err) {
      console.error(err);
      throw err; // 仍然抛出错误，但先进行了处理
    } finally {
      loading.value = false; // 结束加载
    }
  };

  // 设置树引用
  const setTreeRef = (el: MiTreeSelectorInstance | null, tabName: string): void => {
    if (el) {
      treeSelectorRefs.value[tabName] = el;
    } else {
      delete treeSelectorRefs.value[tabName];
    }
  };

  const getTreeRefHandler = (tabName: string) => {
    // 这里提前定义 el 的类型，与 setTreeRef 保持一致
    return (el: MiTreeSelectorInstance | null) => {
      setTreeRef(el, tabName);
    };
  };

  // 标签页点击事件
  function handleTabClick(selectedTab: TabsPaneContext) {
    if (selectedTab.paneName) {
      activePermissionTab.value = selectedTab.paneName.toString();
    }
  }

  // 切换权限类型
  const switchPermissionType = (type: 'all' | 'inherited' | 'assigned', params: any) => {
    if (allRef.value) {
      allRef.value.clearText();
    }
    if (inheritanceRef.value) {
      inheritanceRef.value.clearText();
    }
    activePermissionType.value = type;
    paramsTree.value = params;
    if (type === 'assigned') {
      requestTreeData(params);
    } else if (type === 'all') {
      requesAllTreeData(params);
    } else {
      requestInheritanceTreeData(params);
    }
  };

  // 传入右侧的数据，和原始的右侧新增做对比，获取最终的左侧删除，右侧新增
  function processSpecificData(addTree: TreeNodeCharacter[], originalTree: TreeNodeCharacter[]) {
    const originalIds = new Set(originalTree.map((item: TreeNodeCharacter) => item.id));
    const filterAa = (nodes: TreeNodeCharacter[]): TreeNodeCharacter[] => {
      return nodes
        .map((node) => {
          const isInBb = originalIds.has(node.id);
          const filteredChildren = node.children ? filterAa(node.children) : undefined;
          if (!isInBb || (filteredChildren && filteredChildren.length > 0)) {
            const result: TreeNodeCharacter = {
              id: node.id,
              code: node.code,
              type: node.type,
              appId: node.appId,
            };
            // 如果有过滤后的子节点且不为空，则添加 children 属性
            if (filteredChildren && filteredChildren.length > 0) {
              result.children = filteredChildren;
            }

            return result;
          }
          return null;
        })
        .filter(Boolean) as TreeNodeCharacter[];
    };

    // 新增的
    const addFunctions = filterAa(addTree);
    const extractAllAaIds = (nodes: TreeNodeCharacter[]): Set<number> => {
      const ids = new Set<number>();
      const traverse = (node: TreeNodeCharacter) => {
        ids.add(node.id);
        node.children?.forEach(traverse);
      };
      nodes.forEach(traverse);
      return ids;
    };

    const aaAllIds = extractAllAaIds(addTree);
    const deletedFunctions = (() => {
      console.log('originalTree', originalTree);
      const result: TreeNodeCharacter[] = [];
      const traverseAndCollectLeaves = (nodes: TreeNodeCharacter[]) => {
        nodes.forEach((node) => {
          if (node.children && node.children.length > 0) {
            // 有子节点，继续遍历
            traverseAndCollectLeaves(node.children);
          } else if (!aaAllIds.has(node.id)) {
            // 没有子节点且不在排除列表中，收集叶子节点
            result.push({
              id: node.id,
              code: node.code,
              type: node.type,
              appId: node.appId,
            });
          }
        });
      };

      traverseAndCollectLeaves(originalTree);
      return result;
    })();
    // 整理保存的数据
    return {
      ...paramsTree.value,
      addFunctions,
      deletedFunctions,
    };
  }

  // 处理树组件返回的数据为接口所需要的格式(只拿出子节点)
  const processLeafNodes = (nodes: TreeNodeCharacter[], appMap: AppIdsMap): TreeNodeCharacter[] => {
    const result: TreeNodeCharacter[] = [];
    const findAppId = (id: number): string => {
      const found = Object.entries(appMap).find(([_, ids]) => ids.includes(id));
      return found ? found[0] : '';
    };
    const traverse = (node: TreeNodeCharacter) => {
      if (!node.children || node?.children.length === 0) {
        result.push({
          ...node,
          appId: findAppId(node?.id),
        });
      } else {
        node?.children.forEach(traverse);
      }
    };

    nodes.forEach(traverse);
    return result;
  };

  // 处理保存
  const handleSave = async () => {
    let saveParams: RoleSaveRequest = {
      roleId: roleId.value,
      orgCode: orgCode.value,
      deletedFunctions: [],
      addFunctions: [],
    };
    await nextTick();

    const currentRef = treeSelectorRefs.value[activePermissionTab.value];
    if (currentRef?.getTreeData) {
      try {
        const treeDataItem = currentRef.getTreeData();
        const processedNodes = processLeafNodes(treeDataItem, appCodeArray.value);
        saveParams = processSpecificData(processedNodes, functionalResult.value.authorized1);
      } catch (error) {
        console.error(error);
      }
    } else {
      console.warn('treeSelectorRef 方法不可用，跳过获取选中数据');
    }
    try {
      const res = await getRoleAuthorizationSave(saveParams);
      ElMessage({ message: res.message, type: 'success' });
      requestTreeData(paramsTree.value);
      return res;
    } catch (err) {
      console.error(err);
      throw err;
    }
  };
  return {
    treeSelectorRefs,
    activePermissionTab,
    activePermissionType,
    roleId,
    orgCode,
    treeData,
    treeAddSelect,
    appCodeArray,
    functionalResult,
    formData,
    selectedPermissions,
    propsConfig,
    treeInheritanceData,
    treeAllData,
    loading,
    allRef,
    inheritanceRef,

    setTreeRef,
    handleTabClick,
    switchPermissionType,
    requestTreeData,
    handleSave,
    getTreeRefHandler,
  };
}
